<?php

namespace app\api\controller;

use app\admin\model\member\Payorder;
use app\api\model\BaseModel;
use app\api\model\ConfigModel;
use app\api\model\FeedbackModel;
use app\api\model\HomeOrderModel;
use app\api\model\UserAddressModel;
use app\api\model\UserBankModel;
use app\api\model\UserModel;
use app\api\model\UserMoneyLogModel;
use app\api\model\UserRedbagLogModel;
use app\api\model\UserTokenModel;
use app\api\model\UserWithdrawModel;
use app\api\service\JsonService;
use app\common\controller\Api;
use think\Cache;
use think\Db;
use wx\WXBizDataCrypt;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['phonelogin','login', 'phoneregister'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

     /**
     * 手机号账号密码会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function phonelogin()
    {
        $account = $this->request->post('mobile');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $user =$this->auth->getUserinfo();
            $check = UserModel::checkStatus($user);
                if ($check['code'] != 1) {
                    $this->error($check['msg']);
                }
                $token = generateToken($user->id);
                $userTokenData = [
                    'token' => $token,
                    'update_time' => time(),
                    'expire_time' => expire_time()
                ];
                UserTokenModel::update($userTokenData, ['user_id' => $user->id]);
                $update = [
                    'last_time' => time(),
                    'last_ip' => getIP(),
                ];
                UserModel::userLoginTimeUpdate($update, $user->id);
            return JsonService::successful(__('Logged in successful'), ['token' => $token]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function phoneregister()
    {
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        if (!$mobile || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $user = UserModel::where('mobile', $mobile)->find();
        if (!$user) {
            $ip = getIP();
            $user = UserModel::create([
                'mobile' => $mobile,
                'password' => $password,
                'add_ip' => $ip,
                'last_ip' => $ip,
                'last_time' => time()
            ]);
            $user->invite_code = generateInviteCode($user->id);
            $user->save();
            $token = generateToken($user->id);
            $userTokenData = [
                'user_id' => $user->id,
                'token' => $token,
                'update_time' => time(),
                'expire_time' => expire_time()
            ];
            UserTokenModel::insert($userTokenData);
            return JsonService::successful(__('Logged in successful'), ['token' => $token]);
        } 
        $this->error('获取失败');
    }

     //解密微信用户敏感数据 登录
     public function login()
     {
         $params = $this->request->param();
         if (empty($params['code']) || empty($params['phonecode'])) {
             return JsonService::fail(__('Invalid parameters'));
         }
         $app_id = config('wx.app_id');
         $secret = config('wx.secret');
         $grant_type = "authorization_code"; //授权（必填）
         $code = $params['code'];
         // 拼接url
         $url = "https://api.weixin.qq.com/sns/jscode2session?" . "appid=" . $app_id . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=" . $grant_type;
        //  $url = "https://api.weixin.qq.com/sns/oauth2/access_token?" . "appid=" . $app_id . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=" . $grant_type;
         $result = json_decode(httpRequest($url), true);
         if (empty($result['session_key'])) {
             return JsonService::fail($result);
         }
         $openid = $result['openid'];
         $unionid = isset($result['unionid']) ? $result['unionid'] : '';
        //  $user = UserModel::where('openid', $openid)->find();
         //手机号  是否存在 
         $phone = $this->inphone($params['phonecode']);
         if (!$phone) {
            return JsonService::fail('获取失败！');
         }else{
            $user = UserModel::where('mobile', $phone)->find();
         }
         $ip = getIP();
         Db::startTrans();
         try {
             if (!$user) {
                 $user = UserModel::create([
                     'openid' => $openid,
                     'unionid' => $unionid,
                     'mobile' => $phone,
                     'nickname' => $params['nickName'],
                     'avatar' => $params['avatarUrl'],
                     'add_ip' => $ip,
                     'last_ip' => $ip,
                     'last_time' => time()
                 ]);
                 $user->save();
                 $token = generateToken($user->id);
                 $userTokenData = [
                     'user_id' => $user->id,
                     'token' => $token,
                     'update_time' => time(),
                     'expire_time' => expire_time()
                 ];
                 UserTokenModel::insert($userTokenData);
             } else {
                 $check = UserModel::checkStatus($user);
                 if ($check['code'] != 1) {
                     $this->error($check['msg']);
                 }
                 $token = generateToken($user->id);
                 $userTokenData = [
                    'token' => $token,
                    'update_time' => time(),
                    'expire_time' => expire_time()
                 ];
                 if(UserTokenModel::where('user_id',$user->id)->find()){
                    UserTokenModel::update($userTokenData, ['user_id' => $user->id]);
                 }
                 else{
                    $userTokenData['user_id'] =$user->id;
                    UserTokenModel::create($userTokenData);
                 }
                 $update = [
                    'add_ip' => $ip,
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'last_time' => time(),
                    'last_ip' => getIP(),
                 ];
                 if(!$user['nickname']){
                    $update['nickname'] = $params['nickName'];
                    $update['avatar'] = $params['avatarUrl'];
                 }
                 UserModel::userLoginTimeUpdate($update, $user->id);
             }
             Db::commit();
             return JsonService::successful(__('Logged in successful'), ['token' => $token, 'info' => $user]);
         } catch (\Exception $e) {
             Db::rollback();
             return JsonService::fail($e->getMessage());
         }
     }
 

    //获取用户微信手机号
    public function phone()
    {
        $params = $this->request->param();
        if (empty($params['code'])) {
            $this->error(__('Invalid parameters'));
        }
        $app_id = config('wx.app_id');
        $secret = config('wx.secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$secret}";
        $result = file_get_contents($url);
        if (!$result) {
            return JsonService::fail('获取微信token错误');
        }
        $result = json_decode($result, true);
        if (isset($result['errcode'])) {
            return JsonService::fail($result['errmsg']);
        }
        $access_token = $result['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $result = httpRequest($url, ['code' => $params['code']], 'POST', 'json');
        if (!$result) {
            return JsonService::fail('获取微信手机号错误');
        }
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return JsonService::fail($result['errmsg']);
        }
        $phone = $result['phone_info']['purePhoneNumber'];
        if (UserModel::update(['mobile'=>$phone], ['id' =>  $this->request->uid])) {
            return JsonService::successful(UserModel::info($this->request->uid));
        } else {
            return JsonService::fail('失败!');
        }
    }


    public function inphone($code)
    {
        $app_id = config('wx.app_id');
        $secret = config('wx.secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$secret}";
        $result = file_get_contents($url);
        if (!$result) {
            return false;
        }
        $result = json_decode($result, true);
        if (isset($result['errcode'])) {
            return false;
        }
        $access_token = $result['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $result = httpRequest($url, ['code' => $code], 'POST', 'json');
        if (!$result) {
            return false;
        }
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return false;
        }
        return $result['phone_info']['purePhoneNumber'];
        // if (UserModel::update(['mobile'=>$phone], ['id' =>  $this->request->uid])) {
        //     return JsonService::successful(UserModel::info($$this->request->uid));
        // } else {
        //     return JsonService::fail('失败!');
        // }
    }

    //获取用户信息接口
    public function info()
    {
        return JsonService::successful( UserModel::info($this->request->uid));
    }

    public function save()
    {
        return JsonService::successful(UserModel::update($this->request->param(), ['id' => $this->request->uid]));
    }
    //意见反馈
    public function feedback()
    {
        $params = $this->request->param();
        if (empty($params['content'])) {
            return JsonService::fail('参数错误');
        }
        $params['images'] = $params['images'];
        $params['content'] = htmlspecialchars($params['content']);
        $params['user_id'] = $this->request->uid;
        if (FeedbackModel::create($params)) {
            return JsonService::successful('提交成功');
        }
        return JsonService::fail('提交失败');
    }

   
    //余额明细
    public function moneyDetail()
    {
        $params = $this->request->param();
        $params['user_id'] = $this->request->uid;
        $list = UserMoneyLogModel::lst($params);
        return JsonService::success($list);
    }

    //订单支付
    public function orderPay()
    {
        $params = $this->request->param();
        if (empty($params['price']) || empty($params['num'])) {
            return JsonService::fail('price-num参数错误');
        }
        $params['user_id'] = $this->request->uid;
        $order = Payorder::createOrder($params);
        if (!$order) {
            return JsonService::fail('失败');
        }
        $result = Payorder::pay($order);
        if (is_array($result)) {
            return JsonService::successful($result);
        }
        return JsonService::fail('失败');
    }

    public function orderTnePay()
    {
        $params = $this->request->param();
        if (empty($params['id'])) {
            return JsonService::fail('price-num参数错误');
        }
        $order = Payorder::find($params['id']);
        if (!$order) {
            return JsonService::fail('失败');
        }
        $result = Payorder::pay($order);
        if (is_array($result)) {
            return JsonService::successful($result);
        }
        return JsonService::fail($result);
    }
    //订单列表
    public function payorderList()
    {
        $list = Payorder::lst($this->request->uid,$this->request->param());
        return JsonService::successful($list);
    }

    /**
     * curl方法
     *
     *
     */
    public function https_curl_json($url, $data, $type)
    {
        $file = 'wx_getcode';
        if ($type == 'json') {//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            //$data=json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        BaseModel::log($file, $output);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }




}
